// 修改用户信息
const router = require("koa-router")();
/* 查询所有的普通用户*/
import { ReadFile, WriteFile } from '../utils/ReadWriteFile'
/* 登出 */
router.post("/api/update", async ctx => {
/* 
方法1
data={
    "username": "fassaf",
    "type": "common",
    "newUsername": "xiugai",
    "newPassword": "999999"
}
方法2
params={ "username": "fassaf","type": "common",}
data={ "newUsername": "xiugai","newPassword": "999999"}

*/
      // 传参 params
      // 方法1
      const username = ctx.query.username;
      const type  = ctx.query.type;
      // 方法2
      // const { username, type } = ctx.request.body;
      // const { username, type } = ctx.query.body; //失败
      // 新的用户名和密码 data
      const { newUsername, newPassword } = ctx.request.body;

      console.log(type)
      try {
            let result = await ReadFile(type);
            // 检查新的用户名是否已在数据库
            let resnewUser = result.find(item => item.username == newUsername);
            if (resnewUser) {
                  ctx.body = {
                        code: 400,
                        msg: "用户名重复,请重新修改"
                  }
            } else {
                  // 获取要修改的用户信息，修改为新的用户信息
                  let resUpdate = result.find(item => item.username == username);
                  // 查找到要修改的用户
                  if (resUpdate) {
                        /* 修改用户信息 */
                        resUpdate.username = newUsername;
                        resUpdate.password = newPassword;
                        WriteFile({ type, result })
                        // await jsonfile.writeFile(process.cwd() + `/data/${type}.json`, result);
                        ctx.body = {
                              code: 200,
                              msg: "修改成功"
                        }
                  } else {
                        ctx.body = {
                              code: 400,
                              msg: "参数错误,修改失败"
                        }
                  }
                  
            }

      } catch (err) {
            ctx.body = {
                  msg: "请求参数不合法",
                  code: 400
            }
      }

})
module.exports = router;




